<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/11/7 16:08
 */

header('Content-Type: text/xml; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
$arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
$str_dir = array_pop($arr_dir);
define('DEFAULT_SOURCE_ID', $str_dir);

//http公共入口
class import extends \ns_model\message\message_queue
{
    /**
     *  参数
     * @var unknown
     */
    public $mixed_params = null;

    /**
     * 注入消息队列模板
     * @var unknown
     */
    public $arr_in_message = array(
        'base_info'=>array(
            'nns_message_time'=>'', //上游消息时间  年月日时分秒毫秒
            'nns_message_id'=>'',  //上游消息ID
            'nns_cp_id'=>'', //上游CP标示
            'nns_message_xml'=>'',  //上游原始的信息  可以为字符串 | xml | json
            'nns_message_content'=>'',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action'=>'', //操作 行为
            'nns_type'=>'', //消息 类型
            'nns_name'=>'',  //消息名称
            'nns_package_id'=>'',  //包ID（只对天威用 后期废用）
            'nns_xmlurlqc'=>'', //广州电信悦ME MD5摘要
            'nns_encrypt'=>'', //广州电信悦ME 加密串
            'nns_content_number'=>'', //xml文件中包含的内容数量
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );

    /**
     * 初始化
     */
    public function __construct()
    {
        //加载 xml转为数组的np库
        \ns_core\m_load::load_np("np_xml_to_array.class.php");
        //初始化obj DC
        m_config::get_dc();
        //接收日志处理
        \m_config::write_message_receive_log("-----------消息接收开始-----------", DEFAULT_SOURCE_ID);
        $data = $_POST;
        \m_config::write_message_receive_log("接收POST消息：". var_export($data, true), DEFAULT_SOURCE_ID);
        if(empty($data))
        {
            $data = file_get_contents('php://input');
            \m_config::write_message_receive_log("接收流文件消息：". var_export($data, true), DEFAULT_SOURCE_ID);
            if (is_object(simplexml_load_string($data)))
            {
                $data = array(
                    'cmspost' => $data
                );
            }
        }
        //传入的值有可能是http的query格式的值，并且进行了URLEDcode加密
        if(!is_array($data))
        {
            $data = $this->_deal_import_data($data);
        }
        $this->mixed_params = $data;
    }

    /**
     * 特殊处理传入的值
     * @author  <feijian.gao@starcor.cn>
     * @date	2017年5月22日17:38:03
     *
     * @param  array  $data  	参数值
     * @return array  $arr_tmp  处理之后返回参数
     */
    public function _deal_import_data($data)
    {
        $arr_tmp = array();
        $data = urldecode($data);
        parse_str($data,$arr_tmp);
        return $arr_tmp;
    }

    /**
     * 注入
     * @return string |string
     */
    public function import()
    {
        //原始数据存储的字段
        $this->arr_in_message['base_info']['nns_message_xml'] = is_array($this->mixed_params) ? json_encode($this->mixed_params,JSON_UNESCAPED_UNICODE) : $this->mixed_params;
        //cmspost xml数据
        $xml_data = $this->mixed_params['cmspost'];
        if(m_config::is_xml($xml_data))
        {
            $dom = new DOMDocument('1.0', 'utf-8');
            $dom->loadXML($xml_data);
            $cmspost = $dom->saveXML();
            $xml_arr_data = np_xml_to_array::parse2($cmspost);
            $this->arr_in_message['base_info']['nns_cp_id'] = isset($xml_arr_data['cp_id']) ? $xml_arr_data['cp_id'] : '';
        }
        else if (is_array($this->mixed_params) && !empty($this->mixed_params))
        {
            $xml_arr_data = $this->mixed_params;
            $this->arr_in_message['base_info']['nns_cp_id'] = isset($xml_arr_data['cpid']) ? $xml_arr_data['cpid'] : '';
        }
        else
        {
            \m_config::write_message_receive_log("cmspost参数传入的内容非xml，执行错误", DEFAULT_SOURCE_ID);
            return $this->exec(m_config::return_data(1,'cmspost参数传入的内容非xml，执行错误'));
        }

        //消息ID
        if (!is_array($xml_arr_data) || empty($xml_arr_data))
        {
            $this->arr_in_message['base_info']['nns_message_id'] = np_guid_rand();
            $this->arr_in_message['base_info']['nns_cp_id'] = DEFAULT_SOURCE_ID;
            $this->arr_in_message['base_info']['nns_message_content'] = "没有nns_message_content字段，作为占位符占存";
            return $this->exec(m_config::return_data(1,'没有nns_message_content字段'));
        }
        $time = \m_config::get_micro_time();
        $this->arr_in_message['base_info']['nns_message_id'] = isset($xml_arr_data['msgid']) ? $xml_arr_data['msgid'] : '';
        $this->arr_in_message['base_info']['nns_message_time'] = $time;
        $str_content_url = isset($xml_arr_data['url']) ? trim($xml_arr_data['url']) : '';

        $file_name = $this->arr_in_message['base_info']['nns_message_id'] . '.xml';
        $save_xml_path = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/data/message_receive_log/import_xml/' . $this->arr_in_message['base_info']['nns_cp_id'] . '/' . date("Y-m-d") . '/';

        if (!is_dir($save_xml_path))
        {
            mkdir($save_xml_path, 0777, true);
            if(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
            {
                $stat = stat($save_xml_path);
                $result_chown = (posix_getpwuid($stat['uid']));
                if(!isset($result_chown['name']) || $result_chown['name'] != 'www')
                {
                    chown($result_chown, 'www');
                }
            }
        }
        $abs_path = $save_xml_path . $file_name;

        //获取  ftp 、http 文件内容（此内容是队列需要后期解析的内容）（以项目情况而定）
        if(strlen($str_content_url) > 0)
        {
            $result_content = m_config::get_mix_url_content_and_save($str_content_url, $abs_path, 600, true);
        }
        elseif (!empty($xml_arr_data['xml']) && m_config::is_xml($xml_arr_data['xml']))
        {
            $result_content = m_config::content_to_save($xml_arr_data['xml'], $this->arr_in_message['base_info']['nns_message_id'], $abs_path);
        }
        else
        {
            return $this->exec(m_config::return_data(1,'请求参数内容既不是url也不是xml，执行错误'));
        }

        if($result_content['ret'] !=0)
        {
            $this->arr_in_message['base_info']['nns_message_state'] = '1';
            $this->arr_in_message['base_info']['nns_message_content'] = $result_content['reason'];
        }
        else if(!isset($result_content['data_info']) || strlen($result_content['data_info']) <1)
        {
            $this->arr_in_message['base_info']['nns_message_state'] = '1';
            $this->arr_in_message['base_info']['nns_message_content'] = "获取内容为空地址:[{$str_content_url}]";
        }
        else
        {
            $this->arr_in_message['base_info']['nns_message_content'] = @file_get_contents($result_content['data_info']);
        }
        //消息队列入库方法
        $result = $this->push($this->arr_in_message);
        return $this->exec($result);
    }

    /**
     * @param $result
     * @return string
     */
    public function exec($result)
    {
        if($result['ret'] != 0)
        {
            \m_config::write_message_receive_log("注入结果失败：".var_export($result,true), DEFAULT_SOURCE_ID);
            return "<result  ret=\"-1\"  reason=\"{$result['reason']}\"></result>";
        }
        else
        {
            \m_config::write_message_receive_log("注入结果成功", DEFAULT_SOURCE_ID);
            return "<result  ret=\"{$result['ret']}\"  reason=\"success\"></result>";
        }
    }
    /**
     * 类销毁
     */
    public function __destruct()
    {
        \m_config::write_message_receive_log("-----------消息接收结束-----------", DEFAULT_SOURCE_ID);
    }
}
$http_import = new import();
$result_import = $http_import->import();
echo $result_import;